const STORAGE_KEY = 'search-list';
const HISTORY_MAX = 20;

export default {
	namespaced: true,
	// 独立命名空间
	state: () => {
		// 优先从 storage 中读取
		return {
			searchData: uni.getStorageSync(STORAGE_KEY) || []
		}
	},
	mutations: {
		/**
		 * 保存数据到 storage
		 */
		saveToStorage(state) {
			uni.setStorage({
				key: STORAGE_KEY,
				data: state.searchData
			})
		},
		/**
		 * 添加数据
		 */
		addSearchData(state, val) {
			if (!val) return
			// 找到返回下标
			const index = state.searchData.findIndex((item) => item === val)
			// 证明存在对应的搜索内容
			if (index !== -1) {
				// 去除重复
				state.searchData.splice(index, 1)
			}
			if (state.searchData.length > HISTORY_MAX) {
				state.searchData.splice(HISTORY_MAX, 1)
			}
			// 判断是否超过了最大缓存数量
			state.searchData.unshift(val);
			this.commit('search/saveToStorage')
		},
		removeAllSearchData(state) {
			state.searchData = []
			this.commit('search/saveToStorage')
		},
		removeSearchData(state, index) {
			state.searchData.splice(index, 1)
			this.commit('search/saveToStorage')
		}
	}
}
